import { PlayerSpawnAfterEvent, world } from "@minecraft/server";
import { GameComponent } from "@sapi-game/main";
import { HideAndSeekMainState } from "../mainState";
import { HideAndSeekPlayer, HideAndSeekRole } from "../player";
import { SeekerEquipment } from "./seekerEquip";

type DeathType = "catch" | "die";

export class HideAndSeekRespawn extends GameComponent<HideAndSeekMainState> {
    callBacks: ((player: HideAndSeekPlayer, type: DeathType) => void)[] = [];

    override onAttach(): void {
        this.subscribe(world.afterEvents.playerSpawn, (t) =>
            this.handleSpawn(t)
        );
        this.subscribe(world.afterEvents.entityDie, (t) => {
            const player = this.context.players.getById(t.deadEntity.id);
            if (player) {
                this.handleDie(player);
            }
        });
    }

    private handleDie(player: HideAndSeekPlayer) {
        //死亡处理
        if (player.role == HideAndSeekRole.Hider) {
            this.runCallBacks(player, "catch");
        } else if (player.role == HideAndSeekRole.Seeker) {
            this.runCallBacks(player, "die");
        }
    }

    private handleSpawn(t: PlayerSpawnAfterEvent) {
        const gamePlayer = this.context.players.getById(t.player.id);
        if (!gamePlayer) return;
        //追捕者重发装备
        if (gamePlayer.role == HideAndSeekRole.Seeker) {
            this.state.getComponent(SeekerEquipment).loadEquipment(gamePlayer);
        }
    }

    private runCallBacks(p: HideAndSeekPlayer, type: DeathType) {
        for (let callback of this.callBacks) {
            try {
                callback(p, type);
            } catch (err) {}
        }
    }

    sub(callback: (player: HideAndSeekPlayer, type: DeathType) => void) {
        this.callBacks.push(callback);
    }
}
